<template>
  <div class="qrcode-shop-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>店铺二维码生成</span>
        </div>
      </template>
      
      <div class="form-container">
        <el-form ref="formRef" :model="formData" label-width="80px">
          <el-form-item label="选择店铺" prop="shopId">
            <el-select v-model="formData.shopId" placeholder="请选择店铺" style="width: 200px">
              <el-option
                v-for="shop in shops"
                :key="shop.id"
                :label="shop.name"
                :value="shop.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="generateQrCode" :loading="loading">生成二维码</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>其他二维码</span>
        </div>
      </template>
      <div class="form-container">
        <el-form ref="formRef" :model="formData" label-width="80px">
          <el-form-item>
            <el-button type="success" @click="generateOpticalQrCode" :loading="loading">生成视光版二维码</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- 二维码弹窗 -->
    <el-dialog
      title="店铺二维码"
      v-model="dialogVisible"
      width="400px"
      @close="handleClose"
    >
      <div class="qrcode-dialog-content">
        <div class="qrcode-wrapper" ref="qrcodeWrapper">
          <img :src="qrcodeUrl" alt="店铺二维码" v-if="qrcodeUrl" class="qrcode-image"/>
          <div class="shop-id-overlay" v-if="currentShopId">{{ currentShopId }}</div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveQrCode">保存二维码</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useCool } from '/@/cool';
import type { FormInstance } from 'element-plus';

// 表单引用
const formRef = ref<FormInstance>();
// 二维码容器引用
const qrcodeWrapper = ref<HTMLElement | null>(null);

// 表单数据
const formData = ref({
  shopId: ''
});

// 店铺列表
const shops = ref<Array<{ id: string; name: string }>>([]);

// 状态变量
const dialogVisible = ref(false);
const qrcodeUrl = ref<string>('');
const loading = ref(false);
const currentShopId = ref<string>('');

// 使用cool-admin的服务
const { service } = useCool();

// 加载店铺列表
const loadShops = async () => {
  try {
    // 调用实际接口获取店铺列表
    service.order.shop.getSelectList().then((res: any) => {
        if (res) {
            // 显式指定shopList的类型，确保与shops.value类型匹配
            const shopList: Array<{ id: string; name: string }> = [];
            res.forEach((item: any) => {
                // 确保类型安全转换
                shopList.push({
                    id: String(item.value),
                    name: String(item.label)
                })
            })
            shops.value = shopList;
        }
    });
  } catch (error) {
    ElMessage.error('获取店铺列表失败');
    console.error('获取店铺列表失败:', error);
  }
};

// 生成二维码
const generateOpticalQrCode = async () => {
  
  loading.value = true;
  try {
    // 使用cool-admin的服务方式发送请求
    const response = await service.qrcode.qrcode.makeCustomQrcode({
      scene: 'sceneId:1'
    });
    
    // 确保response是字符串类型
    qrcodeUrl.value = typeof response === 'string' ? response : String(response);
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error('生成二维码失败');
    console.error('生成二维码失败:', error);
  } finally {
    loading.value = false;
  }
};

// 生成二维码
const generateQrCode = async () => {
  if (!formData.value.shopId) {
    ElMessage.warning('请先选择店铺');
    return;
  }
  
  loading.value = true;
  try {
    // 使用cool-admin的服务方式发送请求
    const response = await service.qrcode.qrcode.makeShopQrcode({
      shopId: formData.value.shopId
    });
    
    // 确保response是字符串类型
    qrcodeUrl.value = typeof response === 'string' ? response : String(response);
    currentShopId.value = formData.value.shopId;
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error('生成二维码失败');
    console.error('生成二维码失败:', error);
  } finally {
    loading.value = false;
  }
};

// 保存二维码
const saveQrCode = () => {
  if (!qrcodeUrl.value || !currentShopId.value) {
    ElMessage.warning('暂无二维码可保存');
    return;
  }
  
  try {
    // 创建Canvas元素用于绘制包含店铺ID的二维码
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    
    if (!ctx) {
      throw new Error('无法获取Canvas上下文');
    }
    
    const qrCodeImage = new Image();
    qrCodeImage.crossOrigin = 'anonymous'; // 解决跨域问题
    
    qrCodeImage.onload = () => {
      // 设置Canvas尺寸
      const qrSize = 300; // 二维码尺寸
      const padding = 40; // 边距
      const sizeWithPadding = qrSize + padding * 2;
      
      canvas.width = sizeWithPadding;
      canvas.height = sizeWithPadding;
      
      // 绘制白色背景
      ctx.fillStyle = '#ffffff';
      ctx.fillRect(0, 0, sizeWithPadding, sizeWithPadding);
      
      // 绘制二维码图片
      ctx.drawImage(qrCodeImage, padding, padding, qrSize, qrSize);
      
      // 设置文字样式
      ctx.fillStyle = '#333333';
      ctx.font = 'bold 16px Arial';
      ctx.textAlign = 'right';
      ctx.textBaseline = 'bottom';
      
      // 在右下角绘制店铺ID
      const textX = sizeWithPadding - padding + 5;
      const textY = sizeWithPadding - padding + 5;
      
      // 绘制背景矩形使文字更清晰
      const textWidth = ctx.measureText(currentShopId.value).width + 10;
      const textHeight = 25;
      ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
      ctx.fillRect(textX - textWidth, textY - textHeight, textWidth, textHeight);
      
      // 绘制文字
      ctx.fillStyle = '#333333';
      ctx.fillText(currentShopId.value, textX, textY);
      
      // 转换Canvas为图片并下载
      canvas.toBlob((blob) => {
        if (blob) {
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = `shop_${currentShopId.value}_qrcode.png`;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          
          // 释放URL对象
          URL.revokeObjectURL(link.href);
          
          ElMessage.success('二维码保存成功');
        }
      });
    };
    
    qrCodeImage.onerror = () => {
      throw new Error('加载二维码图片失败');
    };
    
    qrCodeImage.src = qrcodeUrl.value;
  } catch (error) {
    ElMessage.error('二维码保存失败');
    console.error('保存二维码失败:', error);
  }
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
  // 可以在这里添加清理逻辑
};

// 组件挂载时加载店铺列表
onMounted(() => {
  loadShops();
});
</script>

<style scoped>
.qrcode-shop-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-container {
  padding: 20px 0;
}

.qrcode-dialog-content {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.qrcode-wrapper {
  position: relative;
  width: 250px;
  height: 250px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.qrcode-image {
  max-width: 100%;
  max-height: 100%;
}

.shop-id-overlay {
  position: absolute;
  bottom: 5px;
  right: 5px;
  font-size: 12px;
  color: #333;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 2px 5px;
  border-radius: 3px;
  font-weight: bold;
}
</style>